package com.yoyo.framework.shiro.service;

import com.yoyo.common.constant.Constants;
import com.yoyo.common.constant.ShiroConstants;
import com.yoyo.common.core.domain.entity.SysUser;
import com.yoyo.common.exception.user.UserPasswordNotMatchException;
import com.yoyo.common.exception.user.UserPasswordRetryLimitExceedException;
import com.yoyo.common.utils.MessageUtils;
import com.yoyo.framework.manager.AsyncManager;
import com.yoyo.framework.manager.factory.AsyncFactory;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zyl
 * @Date 2021/6/27 -10:58
 */
@Component
public class SysPasswordService {
    @Autowired
    private CacheManager cacheManager;
    private Cache<String, AtomicInteger> loginRecordCache;
    @Value("${user.password.maxRetryCount}")
    private String maxRetryCount;

    @PostConstruct
    public void init() {
        loginRecordCache = cacheManager.getCache(ShiroConstants.LOGINRECORDCACHE);
    }

    public void validate(SysUser user, String password) {
        String loginName = user.getLoginName();
        AtomicInteger retryCount = loginRecordCache.get(loginName);
        if (retryCount == null) {
            retryCount = new AtomicInteger(0);
            loginRecordCache.put(loginName, retryCount);
        }
        if (retryCount.incrementAndGet() > Integer.valueOf(maxRetryCount).intValue()) {
            AsyncManager.me().execute(AsyncFactory.recordLoginInfo(loginName, Constants.LOGIN_FAIL, MessageUtils.message("user.password.retry.limit.exceed", maxRetryCount)));
            throw new UserPasswordRetryLimitExceedException(Integer.valueOf(maxRetryCount).intValue());
        }
           if (!matches(user, password)) {
            AsyncManager.me().execute(AsyncFactory.recordLoginInfo(loginName,Constants.LOGIN_FAIL,MessageUtils.message("user.password.retry.limit.count",retryCount)));
            loginRecordCache.put(loginName,retryCount);
            throw  new UserPasswordNotMatchException();
        }else {
            clearLoginRecordCache(loginName);
        }
    }

    private void clearLoginRecordCache(String loginName) {
        loginRecordCache.remove(loginName);
    }

    private boolean matches(SysUser user, String password) {
        return user.getPassword().equals(encryptPassword(user.getLoginName(), password, user.getSalt()));
    }

    private String encryptPassword(String loginName, String password, String salt) {
        return new Md5Hash(loginName + password + salt).toHex();
    }

//    public static void main(String[] args) {
//        String  loginName="admin";
//        String  password="admin";
//        String  salt="123";
//        String s = new Md5Hash(loginName + password + salt).toHex();
//        System.out.println(s);
//    }
}
